//
//  WXPay.m
//  PayDemo
//
//  Created by 红沙尘 on 2018/12/14.
//  Copyright © 2018年 红沙尘. All rights reserved.
//

#import "WXPay.h"
#import <CommonCrypto/CommonDigest.h>

@implementation WXPay

#pragma mark -  微信支付本地签名
//创建发起支付时的sign签名
+ (NSString *)createMD5SingForPayWithAppID:(NSString *)appid_key
                                 partnerid:(NSString *)partnerid_key
                                  prepayid:(NSString *)prepayid_key
                                   package:(NSString *)package_key
                                  noncestr:(NSString *)noncestr_key
                                 timestamp:(UInt32)timestamp_key {
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    [signParams setObject:appid_key forKey:@"appid"];//微信appid 例如wxfb132134e5342
    [signParams setObject:noncestr_key forKey:@"noncestr"];//随机字符串
    [signParams setObject:package_key forKey:@"package"];//扩展字段  参数为 Sign=WXPay
    [signParams setObject:partnerid_key forKey:@"partnerid"];//商户账号
    [signParams setObject:prepayid_key forKey:@"prepayid"];//此处为统一下单接口返回的预支付订单号
    [signParams setObject:[NSString stringWithFormat:@"%u",timestamp_key] forKey:@"timestamp"];//时间戳

    if ([signParams[@"timestamp"] length] > 10) {
        return @"时间戳必须是10位";
    }
    
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [signParams allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[signParams objectForKey:categoryId] isEqualToString:@""]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"sign"]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"key"]
            ) {
            [contentString appendFormat:@"%@=%@&", categoryId, [signParams objectForKey:categoryId]];
        }
    }
    //添加商户密钥key字段  API 密钥
    NSString *miyao = @"";
    if (miyao.length == 0) {
        return @"密钥不能为空";
    }
    [contentString appendFormat:@"key=%@", miyao];
    NSString *result = [self md5:contentString];//md5加密
    return result;
}

+ (NSString *)md5:(NSString *)string {
    if(string == nil || [string length] == 0) return nil;
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
    
    CC_MD5([string UTF8String], (int)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest);
    
    NSMutableString *ms = [NSMutableString string];
    
    for(i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ms appendFormat: @"%02x", (int)(digest[i])];
    }
    
    return [ms copy];
}

@end
